package com.zidian.study.activity;

import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import com.zidian.study.adapter.InteractionQuestionAdapter;
import com.zidian.study.bean.QuestionOneBean;
import com.zidian.study.globa.Constant;
import com.zidian.study.globa.ToolBarActivity;
import com.zidian.study.utils.GetUserInfo;
import com.zidian.study.utils.ToastUtil;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.MediaType;
import com.zidian.student.trucks.R;

/**
 * Created by Administrator on 2016/8/25 0025.
 * <p/>
 * 问卷详情界面
 */
public class InteractionQstDetailActivity extends ToolBarActivity {

    @Bind(R.id.question_evaluate_type)
    TextView questionEvaluateType;
    @Bind(R.id.question_evaluate_from)
    TextView questionEvaluateFrom;
    @Bind(R.id.question_evaluate_time)
    TextView questionEvaluateTime;
    @Bind(R.id.tab_item)
    LinearLayout tabItem;
    @Bind(R.id.question_title_count)
    TextView questionTitleCount;
    @Bind(R.id.title_item)
    LinearLayout titleItem;
    @Bind(R.id.answer_item)
    TextView answerItem;
    @Bind(R.id.list)
    RecyclerView mRecyclerView;
    @Bind(R.id.submit_btn)
    TextView submitBtn;

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    private List<Map<String, String>> data = new ArrayList<>();
    private Map<Integer, Map<String, String>> update = new HashMap<>();
    private InteractionQuestionAdapter adapter;
    private Handler handler = new Handler();
    private int questionnaireId;
    private Map<Integer, Integer> so = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setToolbarView(R.layout.toolbar_left);
        setContentView(R.layout.activity_interaction_questionaire_2);
        ButterKnife.bind(this);
        setTitle("问卷调查");

        initView();
        initData();


    }

    public int selectItem = -1;

    public void initView() {
        questionnaireId = this.getIntent().getIntExtra("questionnaireId", 0);
        adapter = new InteractionQuestionAdapter(this, data);
        final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(adapter);


        adapter.setOnItemClickListener(new InteractionQuestionAdapter.OnChoseItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                int temp = 0;
                for (int i = 0; i < data.size(); i++) {
                    data.get(i).put("result", position + "");
                }

                if (count == -1) {
                    temp = questionBean.getData().getQuestion().size() - 1;
                } else {
                    temp = count - 1;
                }

                selectItem = position;
                Map<String, String> map = new HashMap<String, String>();
                map.put("type", questionBean.getData().getQuestion().get(temp).getQuestionTypes());
                map.put("questionNumber", questionBean.getData().getQuestion().get(temp).getQuestionNumber() + "");
                map.put("stuOption", selectItem + 1 + "");
                update.put(temp, map);
                adapter.notifyDataSetChanged();
            }
        });
        adapter.setOnItemClickListener(new InteractionQuestionAdapter.OnStarItemClickListener() {
            @Override
            public void onItemClick(float rating, int position, RatingBar ratingbar) {
                Log.e("S", rating + "");
                int temp = 0;
                so.put(position, (int) rating);
                for (int i = 0; i < data.size(); i++) {
                    if (so.get(i) == null) {
                        so.put(i, 1);
                    }
                }
                String stuOption = "1" + "!" + so.get(0);
                for (int i = 1; i < data.size(); i++) {
                    stuOption += "_" + (i + 1) + "!" + so.get(i);
                }

                if (count == -1) {
                    temp = questionBean.getData().getQuestion().size() - 1;
                } else {
                    temp = count - 1;
                }
                Map<String, String> map = new HashMap<String, String>();
                map.put("type", questionBean.getData().getQuestion().get(temp).getQuestionTypes());
                map.put("questionNumber", questionBean.getData().getQuestion().get(temp).getQuestionNumber() + "");
                map.put("stuOption", stuOption);
                update.put(temp, map);
            }
        });

        submitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (count == -1) {
                    if (selectItem == -1 && !questionBean.getData().getQuestion().get(questionBean.getData().getQuestion().size() - 1).getQuestionTypes().equals("打分题")) {
                        Snackbar.make(submitBtn,"请选择选项!",Snackbar.LENGTH_SHORT).show();
                    } else {
//                        ToastUtil.showToast(context, "提交");

                        String jsonresult = "";//定义返回字符串
                        JSONObject object = new JSONObject();//创建一个总的对象，这个对象对整个json串

                        try {
                            JSONArray jsonarray = new JSONArray();//json数组，里面包含的内容为pet的所有对象
                            JSONObject jsonObj = new JSONObject();//pet对象，json形式

                            jsonObj.put("questionnaireId", questionnaireId);//向pet对象里面添加值
                            jsonObj.put("respondentId", GetUserInfo.getStudentId(context));

                            for (int i = 0; i < questionBean.getData().getQuestion().size(); i++) {
                                JSONObject jsonObjAnswer = new JSONObject();//pet对象，json形式
                                jsonObjAnswer.put("questionNumber", update.get(i).get("questionNumber"));
                                jsonObjAnswer.put("stuOption", update.get(i).get("stuOption"));
                                jsonarray.put(jsonObjAnswer);
                            }

                            jsonObj.put("answerResults", jsonarray);
                            jsonresult = jsonObj.toString();//生成返回字符串

                            final String finalJsonresult = jsonresult;
                            new Thread() {
                                @Override
                                public void run() {
                                    updataJson(finalJsonresult);
                                }
                            }.start();

                            Log.e("RESULT", jsonresult);
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }


                    }
                } else {
                    if (selectItem == -1 && !questionBean.getData().getQuestion().get(count - 1).getQuestionTypes().equals("打分题")) {
                        Snackbar.make(submitBtn,"请选择选项!",Snackbar.LENGTH_SHORT).show();
                    } else {
                        getDataref();
                        selectItem = -1;
                    }

                }
            }


//            }
        });

    }


    public void initData() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getList();
            }
        }, 1500);


    }


    private QuestionOneBean questionBean;
    private List<QuestionOneBean.DataBean.QuestionBean.OptionsBean> questionData = new ArrayList<>();


    private void getList() {


        String url = Constant.URL_TEACHER + "Questionnaire/selectQuestionnaireParticulars";

        Map<String, String> map = new HashMap<>();
        map.put("questionnaireId", questionnaireId + "");
        map.put("operatorId", GetUserInfo.getStudentId(context));
        map.put("operatorType", "学生");
        map.put("token", GetUserInfo.getToken(context));


        OkHttpUtils.post().url(url).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {

                Log.e("T", response);

                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {

                        if (resultCode == 201) {
                            return;
                        }

                        ToastUtil.showToast(InteractionQstDetailActivity.this, "提交失败！");
                        return;
                    }

                } catch (JSONException e) {


                }

                Gson gson = new Gson();
                questionBean = gson.fromJson(response, QuestionOneBean.class);
//
                if (questionBean.isSuccess()) {
                    questionEvaluateType.setText(questionBean.getData().getQuestionnaireTitle());
                    questionEvaluateFrom.setText(questionBean.getData().getPublisher());
                    questionEvaluateTime.setText(questionBean.getData().getReleaseTime());
                    getDataref();
                }

            }
        });


    }

    @Override
    protected void onStop() {
        super.onStop();
        count = 0;
    }

    public static int count = 0;

    /**
     * 获取测试数据
     */
    private void getDataref() {
//        questionData = questionBean.getData()

        if (count >= questionBean.getData().getQuestion().size() - 1) {
            submitBtn.setText("提交");
        } else {
            submitBtn.setText("下一题");
        }
        data.clear();

        if (count != -1) {
            questionTitleCount.setText(questionBean.getData().getQuestion().get(count).getQuestioncontent());

            for (int j = 0; j < questionBean.getData().getQuestion().get(count).getOptions().size(); j++) {
                Map<String, String> map = new HashMap<>();
                map.put("optionsDescribe", questionBean.getData().getQuestion().get(count).getOptions().get(j).getOptionsDescribe());
                map.put("option", questionBean.getData().getQuestion().get(count).getOptions().get(j).getOption());
                map.put("result", "");
                data.add(map);
            }

            if (questionBean.getData().getQuestion().get(count).getQuestionTypes().equals("打分题")) {
                for (int i = 0; i < data.size(); i++) {
                    if (so.get(i) == null) {
                        so.put(i, 1);
                    }
                }
                String stuOption = "1" + "!" + so.get(0);
                for (int i = 1; i < data.size(); i++) {
                    stuOption += "_" + (i + 1) + "!" + so.get(i);
                }
                Map<String, String> map = new HashMap<String, String>();
                map.put("type", questionBean.getData().getQuestion().get(count).getQuestionTypes());
                map.put("questionNumber", questionBean.getData().getQuestion().get(count).getQuestionNumber() + "");
                map.put("stuOption", stuOption);
                update.put(count, map);
                adapter.setState(0);
            } else {
                adapter.setState(1);
            }
            mRecyclerView.setAdapter(adapter);
            adapter.notifyDataSetChanged();
            count++;
        }
        if (count > questionBean.getData().getQuestion().size() - 1) {
            count = -1;
        }
    }

    private void updataJson(String json) {
        String Url = "";
        if (questionBean.getData().getQuestionnaireExplain().equals("SCL-90")) {
            Url = Constant.URL_TEACHER + "QuestionnaireSCL/submitQuestionnaireSCL";
        } else {
            Url = Constant.URL_TEACHER + "Questionnaire/insertQuestionnaireSubmit";
        }

        Map<String, String> map = new HashMap<>();
        map.put("questionnaireSubmit", json);
        map.put("studentId", GetUserInfo.getStudentId(context));
        map.put("token", GetUserInfo.getToken(context));


        OkHttpUtils.post().url(Url).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e("E", e.toString());
            }

            @Override
            public void onResponse(String response, int id) {

                Log.e("T", response);

                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {

                        if (resultCode == 201) {
                            return;
                        }

                        ToastUtil.showToast(InteractionQstDetailActivity.this, "提交失败！");
                        return;
                    } else {
                        ToastUtil.showToast(InteractionQstDetailActivity.this, " 成功！");
                        finish();

                    }

                } catch (JSONException e) {


                }
//

            }
        });


    }

}
